package com.taxsearch.controller.room;

import java.sql.Connection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;


import com.taxsearch.dao.room.JingWaiMapper;
import com.taxsearch.dao.room.RoomManagementMapper;
import com.taxsearch.dao.room.RoomSelectMapper;
import com.taxsearch.util.ApiJsonErr;
import com.taxsearch.util.ApiJsonRet;
import com.taxsearch.util.DbUtil;
import com.taxsearch.util.roomutil.RoomUtil;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


/**
 * @description: 房间状态信息查询
 *
 * @author: 杜一平
 *
 * @create: 2018年9月11日-上午10:54:57
 **/
@Controller
@RequestMapping("/HotelAndroid")
public class RoomSelectController {
	/**
	 * 总体说明：
	 * 参数data为一个json字符串，类似为url地址后面的localhost:8080/HotelAndroid/selectRoom?data
	 * ={"status":"1"}中的data 注意调用相关方法解析
	 * 返回值为Object,其中返回ApiJsonErr默认状态为400为失败,ApiJsonRet状态为200为成功
	 */

	// 日志
	public static final Logger logger = LogManager
			.getLogger(RoomManageController.class);
	
	// 统一返回结果
	Object result;

	// 房间管理以及其他的dao层
	@Autowired
	private RoomManagementMapper roommanagementmapper;
	
	// 境外相关操作
	@Autowired
	private JingWaiMapper jingWaiMapper;

	@Autowired
	private RoomSelectMapper roomSelectMapper;
	
	/**
	 * 
	 * @Title: selectWuZhengAndXinXi
	 * @Description: 查询无证权限以及旅馆信息
	 * @param: @param data
	 * @param: @return
	 * @return: Object
	 * @throws
	 */
	@RequestMapping("/selectWuZhengAndXinXi.do")
	@ResponseBody
	public Object selectWuZhengAndXinXi(String data) {
		// 用JDBC查询是否有无证资格
		Connection connection=DB.getConnection();
		HashMap<String, String>mapTempMap = new HashMap<>();
		String hotelId = "";
		try {
			
			// 切换数据源为常规数据源
			DbUtil.setDb("1");
			// 获取相关参数
			Map<String, String> map = RoomUtil.getJsonMap(data);
			hotelId= map.get("HotelId");
			// 校验
			if (RoomUtil.validationData(map)) {
				mapTempMap.put("STATIONID", hotelId);
				mapTempMap.put("LGDZ", "");
				mapTempMap.put("FZR", "");
				mapTempMap.put("WZSP", "1");
				result = new ApiJsonRet("200",mapTempMap);
			}
			
			
			// 查询旅馆信息
			List<HashMap<String, String>>list=roomSelectMapper.selectLvGuanXinXi(hotelId);

			// 如果没有查询旅馆信息
			if(list.size()==0){
				mapTempMap.put("STATIONID", hotelId);
				mapTempMap.put("LGDZ", "");
				mapTempMap.put("FZR", "");
				mapTempMap.put("WZSP", "1");
				return new ApiJsonRet("200",mapTempMap);
			}

			
			Integer i=DB.selectWuzheng(connection,hotelId);
			
			
			// 将是否有无证资格赋值
			mapTempMap=list.get(0);
			if(i == null || i == 0){
				mapTempMap.put("WZSP", "1");
			}else{
				mapTempMap.put("WZSP", "1");
			}
			
			System.out.println("返回成功");
			return new ApiJsonRet("200",mapTempMap);
			
		} catch (Exception e) {
			DB.close(connection);
			logger.error("selectQuanXian-发生错误!!!!!!!!!!!!!!!!!!!!!!!!！", e);
			mapTempMap.put("STATIONID", hotelId);
			mapTempMap.put("LGDZ", "");
			mapTempMap.put("FZR", "");
			mapTempMap.put("WZSP", "1");
			return new ApiJsonRet("200",mapTempMap);
		}
	}
	
	/**
	 * 
	 * @Title: selectOne
	 * @Description: 根据id查询入住信息
	 * @param: @param data
	 * @param: @return  
	 * @return: Object   
	 * @throws
	 */
	@RequestMapping("/selectOne.do")
	@ResponseBody
	public Object selectOne(String data){
		try {
			// 获取相关参数
			Map<String, String> map = RoomUtil.getJsonMap(data);
			// 校验
			if (RoomUtil.validationData(map)) {
				return new ApiJsonErr("有参数为空！");
			}
			String type=map.get("type");
			String RECORDSNO=map.get("RECORDSNO");
			
			List<HashMap<String, String>>list;
			if("0".equals(type)){
				list=roomSelectMapper.selectJingNeiOne(RECORDSNO);
			}else{
				list=roomSelectMapper.selectJingWaiOne(RECORDSNO);
			}
			System.out.println("返回成功");
			result = new ApiJsonRet("200", list);
		} catch (Exception e) {
			logger.error("selectRoom-发生错误!!!!!!!!!!!!!!!!!!!!!!!!", e);
			result = new ApiJsonErr("服务器繁忙,请稍后再试！");
		}
		return result;
					
	}

	/**
	 * 
	 * @Title: selectRoom
	 * @Description: 根据多种条件查询房间状态以及相关入住信息
	 * @param: @param data
	 * @param: @return
	 * @return: Object
	 * @throws
	 */
	@RequestMapping("/selectRoom.do")
	@ResponseBody
	public Object selectRoom(String data) {
		try {
			// 切换数据源为常规数据源
			DbUtil.setDb("1");
			
//			System.out.println(jingWaiMapper.selectJingWai("5101003556"));
			// 获取相关参数
			Map<String, String> map = RoomUtil.getJsonMap(data);
			// 校验
			if (RoomUtil.validationData(map)) {
				return new ApiJsonErr("有参数为空！");
			}
			
			// 获取境内证件类型
			List<HashMap<String, String>>selectIDType=roommanagementmapper.selectIDType();
			Map<String, String>idMap=RoomUtil.getIdType(selectIDType);
			
			// 获取境外证件类型
			List<HashMap<String, String>>JingWaiIdTypeList=jingWaiMapper.selectJingWaiIdType();
			Map<String, String>jingWaiIdMap=RoomUtil.getIdType(JingWaiIdTypeList);
			
			String stationid = map.get("hotelId");
			String status = map.containsKey("status") ? map.get("status") : "5";
			String roomNumString = map.containsKey("RoomNum") ? map
					.get("RoomNum") : null;
			// 获取当前八位系统时间
			String date = RoomUtil.getEightDateNow();
			// 查询预订信息
			List<String> yudingList = roommanagementmapper.selectYuDingXX(
					stationid, date);

			// 查询入住信息
			List<Map<String, String>> ruzhuNumList = roommanagementmapper
					.selectRuZhuXX(stationid, roomNumString);

			// 查询境外入住信息
			List<Map<String, String>>jingWaiRuzhuList=jingWaiMapper.selectJingWai(stationid,null);
			// 将境外加入到原来入住集合中
			ruzhuNumList.addAll(jingWaiRuzhuList);
			
			// 查询该旅馆房间信息
			List<Map<String, String>> roomList = roommanagementmapper
					.selectRoom(stationid, roomNumString);
			
			// 返回json
			JSONArray jsons = new JSONArray();
			// 房间已入住人数map
			Map<String, Integer> isRuzhuMap = new HashMap<>();
			
			// 房间无证状态
			Set<String>wuzhengSet=new HashSet<>();

			for (Map<String, String> room : roomList) {
				// 先默认都是未入住状态
				room.put("roomstatus", "0");
				// 默认房间无证状态为1,就是不显示感叹提示
				room.put("wuzhengStatus", "1");
				// 如果预订房间包含此房间证明为预订状态2
				if (yudingList.contains(room.get("roomnum"))) {
					room.put("roomstatus", "2");
				}

				JSONObject json = (JSONObject) JSONObject.toJSON(room);
				// 添加默认入住信息
				json.put("rzxx", "");
				// 如果此房间在入住房间中则为入住状态1
				for (Map<String, String> ruzhuMap : ruzhuNumList) {
					// 如果房间和入住信息房间匹配
					if (ruzhuMap.get("roomnum").equals(room.get("roomnum"))) {
						// 入住人数map人数加1
						if (isRuzhuMap.containsKey(ruzhuMap.get("roomnum"))) {
							isRuzhuMap
									.put(ruzhuMap.get("roomnum"), isRuzhuMap
											.get(ruzhuMap.get("roomnum")) + 1);
						} else {
							isRuzhuMap.put(ruzhuMap.get("roomnum"), 1);
						}
						
						// 无证审批中，无证审批失败，认证比对失败显示感叹号
						if("0".equals(ruzhuMap.get("wuzhengStatus"))||"3".equals(ruzhuMap.get("wuzhengStatus"))
								||"5".equals(ruzhuMap.get("wuzhengStatus"))){
							wuzhengSet.add(ruzhuMap.get("roomnum"));
						}
						
						// 房间状态改为1已入住
						json.put("roomstatus", "1");
						JSONObject jsonRzxx = new JSONObject();
						jsonRzxx.put("ruzhuid", ruzhuMap.get("RECORDSNO"));
						
						
						// 对境外数据进行处理
						if(ruzhuMap.containsKey("LEIXING")){
							
							jsonRzxx.put("zjlx",jingWaiIdMap.get(ruzhuMap.get("DJ_ZHENGJIANLEIXING")));
							if(RoomUtil.judgeNull(ruzhuMap.get("F_NAME"))){
								jsonRzxx.put("name", ruzhuMap.get("F_FIRSTNAME")+"·"+ ruzhuMap.get("F_LASTNAME"));
							}else{
								jsonRzxx.put("name", ruzhuMap.get("F_NAME"));
							}
						}else{
							// 对境内数据进行处理
							jsonRzxx.put("zjlx",idMap.get(ruzhuMap.get("DJ_ZHENGJIANLEIXING")));
							jsonRzxx.put("name", ruzhuMap.get("DJ_XINGMING"));
						}
						jsonRzxx.put("zjhm", ruzhuMap.get("DJ_ZHENGJIANHAOMA"));
						jsonRzxx.put("rzsj", ruzhuMap.get("DJ_RUZHUSHIJIAN"));

						// 居住人数
						jsonRzxx.put("jzrs", room.get("currentpeople"));
						// 信息存入json数组
						JSONArray jjArray;
						// 插入多个入住人信息数组
						if (!"".equals(json.get("rzxx"))) {
							String arrayString = json.getString("rzxx");
							jjArray = JSON.parseArray(arrayString);
						} else {
							jjArray = new JSONArray();
						}

						jjArray.add(jsonRzxx);
						json.put("rzxx", jjArray);
					}
				}

				// 如果有入住或者预订房间加入到最前面
				if ("1".equals(json.getString("roomstatus"))
						|| "2".equals(json.getString("roomstatus"))) {
					jsons.add(0, json);
				} else {
					jsons.add(json);
				}
				
			}
			
			// 添加是否可以继续入住状态
			if (jsons.size() != 0) {
				for (int j = 0; j < jsons.size(); j++) {
					JSONObject jsonObject = jsons.getJSONObject(j);
					// 当前房间最大人数
					int max = Integer.parseInt(jsonObject
							.getString("maxpeople"));
					// 当前房间号码
					String roomNumberString = jsonObject
							.getString("roomnum");
					// 如果入住map不存在此房间或者此房间现住人数小于最大入住人数则可以继续入住
					if (!isRuzhuMap.containsKey(roomNumberString)
							|| isRuzhuMap.get(roomNumberString) < max) {
						jsonObject.put("isRuzhu", "1");
					} else {
						jsonObject.put("isRuzhu", "0");
					}
					
					// 添加无证状态
					if(wuzhengSet.contains(roomNumberString)){
						jsonObject.put("wuzhengStatus", "0");
					}
				}
			}
			
			
			// 状态为5标识查询所有数据，不为则取出相应状态的房间
			if (!"5".equals(status)) {
				for (int x = 0; x < jsons.size(); x++) {
					JSONObject jsonObjectTemp = jsons.getJSONObject(x);
					if (!jsonObjectTemp.getString("roomstatus").equals(status)) {
						jsons.remove(x);
						// 遍历值减一避免少操作
						x--;
					}
				}
			}
			System.out.println("返回成功");
			result = new ApiJsonRet("200", jsons);
		} catch (Exception e) {
			logger.error("selectRoom-发生错误!!!!!!!!!!!!!!!!!!!!!!!!", e);
			result = new ApiJsonErr("服务器繁忙,请稍后再试！");
		}
		return result;

	}
	
	/**
	 * 
	 * @Title: selectRoomByCondition
	 * @Description: 根据多种条件查询入住情况
	 * @param: @param data
	 * @param: @return
	 * @return: Object
	 * @throws
	 */
	@RequestMapping("/selectRoomByCondition.do")
	@ResponseBody
	public Object selectRoomByDate(String data) {
		try {
			// 切换数据源为常规数据源
			DbUtil.setDb("1");
			// 获取相关参数
			Map<String, String> map = RoomUtil.getJsonMap(data);
			
			// 判断查询时间不能超过最近两个星期
			// 搜索开始时间不为空时
//			if(map.get("startDate")!=null&&!"".equals(map.get("startDate"))){
//				// 如果开始时间与现在相差超过14天
//				if(differentDayByMillisecond(getEightDate(map.get("startDate")), getEightDate(getEightDateNow()))>15){
//					map.put("startDate", getEightDate(minusDate(getEightDate(getEightDateNow()), 14)));
//				}
//			}else{
//				// 搜索条件为空时自动赋最近14天
//				map.put("startDate", getEightDate(minusDate(getEightDate(getEightDateNow()), 14)));
//				map.put("endDate", getEightDateNow());
//			}

			String leixing=map.get("leixing");
			switch (leixing) {
			case "0":
				// 查询入住信息查询条件用map封装
				List<Map<String, String>> ruzhuNumList = roommanagementmapper
						.selectRuZhuXXByDate(map);
				// 查询境外入住
				List<Map<String, String>> jingWaiList = jingWaiMapper
						.selectJingWaiByCondition(map);
				ruzhuNumList.addAll(jingWaiList);
				result = new ApiJsonRet("200", ruzhuNumList);
				break;
			case "1":
				// 查询入住信息查询条件用map封装
				List<Map<String, String>> ruzhuNumList1 = roommanagementmapper
						.selectRuZhuXXByDate(map);		
				result = new ApiJsonRet("200", ruzhuNumList1);
				break;
			case "2":
				// 查询境外入住
				List<Map<String, String>> jingWaiList1 = jingWaiMapper
						.selectJingWaiByCondition(map);
				result = new ApiJsonRet("200", jingWaiList1);
				break;
			default:
				result = new ApiJsonRet("200", "参数错误!");
				break;
			}
		} catch (Exception e) {
			logger.error("selectRoom-发生错误!!!!!!!!!!!!!!!!!!!!!!!!", e);
			result = new ApiJsonErr("服务器繁忙,请稍后再试！");
		}
		System.out.println("返回成功");
		return result;
	}
}
